﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient
Imports System.Windows.Threading
Imports System.Globalization
Imports System.Collections.ObjectModel

Namespace ViewModel

    Public Class ListQueuesPageViewModel
        Inherits PivotItemViewModel

        Private Const IconsRootUri As String = "/Toolkit.Content/"

        Private ReadOnly queueClient As ICloudQueueClient
        Private ReadOnly dispatcher As Dispatcher

        Private _isLoading As Boolean = False
        Private _hasResults As Boolean = True
        Private _prefix As String = String.Empty
        Private _message As String

        Public Sub New()
            Me.New(App.CloudClientFactory.ResolveCloudQueueClient("QueueAndList"), Deployment.Current.Dispatcher)
        End Sub

        Public Sub New(ByVal queueClient As ICloudQueueClient, ByVal dispatcher As Dispatcher)
            Me.queueClient = queueClient
            Me.dispatcher = dispatcher

            Me.CloudQueues = New ObservableCollection(Of ICloudQueue)()
        End Sub

        Public Event Navigate As EventHandler(Of NavigationEventArgs)

        Public Property CloudQueues() As ObservableCollection(Of ICloudQueue)

        Public Property IsLoading() As Boolean
            Get
                Return Me._isLoading
            End Get

            Set(ByVal value As Boolean)
                If Me._isLoading <> value Then
                    Me._isLoading = value
                    Me.NotifyPropertyChanged("IsLoading")
                End If
            End Set
        End Property

        Public Property HasResults() As Boolean
            Get
                Return Me._hasResults
            End Get

            Set(ByVal value As Boolean)
                If Me._hasResults <> value Then
                    Me._hasResults = value
                    Me.NotifyPropertyChanged("HasResults")
                End If
            End Set
        End Property

        Public Property Prefix() As String
            Get
                Return Me._prefix
            End Get

            Set(ByVal value As String)
                If Me._prefix <> value Then
                    Me._prefix = value
                    Me.NotifyPropertyChanged("Prefix")
                End If
            End Set
        End Property

        Public Property Message() As String
            Get
                Return Me._message
            End Get

            Set(ByVal value As String)
                If Me._message <> value Then
                    Me._message = value
                    Me.NotifyPropertyChanged("Message")
                End If
            End Set
        End Property

        Public Sub ListQueues()
            Me.IsLoading = True
            Me.Message = "Listing queues..."
            Try
                Me.queueClient.ListQueues(
                    Me.Prefix,
                    Sub(r)
                        If Me.dispatcher IsNot Nothing Then
                            Me.dispatcher.BeginInvoke(Sub() Me.HandleQueueListResult(r))
                        Else
                            Me.HandleQueueListResult(r)
                        End If
                    End Sub)
            Catch ex As Exception
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", ex.Message)
            End Try
        End Sub

        Public Sub NavigateTo(ByVal navigationUri As Uri)
            Me.RaiseNavigate(navigationUri)
        End Sub

        Public Sub NewQueue()
            Dim newQueueName = String.Format(CultureInfo.InvariantCulture, "Queue{0}", Date.Now.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture)).ToLowerInvariant()

            Me.Message = "Creating new queue..."
            Me.IsLoading = True

            Try
                Dim currentQueue = Me.queueClient.GetQueueReference(newQueueName)
                currentQueue.Create(
                    Sub(creationResult)
                        If Me.dispatcher IsNot Nothing Then
                            Me.dispatcher.BeginInvoke(Sub() Me.HandleQueueCreationResult(currentQueue, creationResult))
                        Else
                            Me.HandleQueueCreationResult(currentQueue, creationResult)
                        End If
                    End Sub)
            Catch ex As Exception
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", ex.Message)
            End Try
        End Sub

        Public Sub DeleteQueue(ByVal queue As ICloudQueue)
            Me.Message = "Deleting queue..."
            Me.IsLoading = True

            Try
                Dim currentQueue = Me.queueClient.GetQueueReference(queue.Name)
                currentQueue.Delete(
                    Sub(deletionResult)
                        If Me.dispatcher IsNot Nothing Then
                            Me.dispatcher.BeginInvoke(Sub() Me.HandleQueueDeletionResult(currentQueue, deletionResult))
                        Else
                            Me.HandleQueueDeletionResult(currentQueue, deletionResult)
                        End If
                    End Sub)
            Catch ex As Exception
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", ex.Message)
            End Try
        End Sub

        Protected Overrides Sub PopulateApplicationBarButtons(ByVal applicationBar As IApplicationBar)
            If applicationBar IsNot Nothing AndAlso applicationBar.Buttons IsNot Nothing Then
                Dim addButton = New ApplicationBarIconButton(New Uri(String.Format(CultureInfo.InvariantCulture, "{0}{1}", IconsRootUri, "appbar.add.rest.png"), UriKind.Relative)) With {.Text = "add queue"}
                AddHandler addButton.Click, Sub(s, e) Me.NewQueue()

                applicationBar.Buttons.Add(addButton)
            End If
        End Sub

        Private Sub HandleQueueListResult(ByVal result As CloudOperationResponse(Of IEnumerable(Of ICloudQueue)))
            If result.Exception Is Nothing Then
                Me.CloudQueues.Clear()
                For Each queue In result.Response
                    Me.CloudQueues.Add(queue)
                Next queue

                Me.HasResults = Me.CloudQueues.Count > 0
                Me.Message = "Listing finished successfully."
            Else
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", result.Exception.Message)
            End If

            Me.IsLoading = False
        End Sub

        Private Sub HandleQueueCreationResult(ByVal currentQueue As ICloudQueue, ByVal creationResult As CloudOperationResponse(Of Boolean))
            If creationResult.Response Then
                Me.CloudQueues.Add(currentQueue)
                Me.HasResults = True
                Me.Message = "Changes saved successfully."
            Else
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", creationResult.Exception.Message)
            End If

            Me.IsLoading = False
        End Sub

        Private Sub HandleQueueDeletionResult(ByVal currentQueue As ICloudQueue, ByVal deletionResult As CloudOperationResponse(Of Boolean))
            If deletionResult.Response Then
                Dim listedQueue = Me.CloudQueues.Where(Function(q) q.Name.Equals(currentQueue.Name, StringComparison.InvariantCulture)).SingleOrDefault()
                If listedQueue IsNot Nothing Then
                    Me.CloudQueues.Remove(listedQueue)
                    Me.Message = "Changes saved successfully."
                End If
            Else
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", deletionResult.Exception.Message)
            End If

            Me.IsLoading = False
        End Sub

        Private Sub RaiseNavigate(ByVal uri As Uri)
            RaiseEvent Navigate(Me, New NavigationEventArgs(Nothing, uri))
        End Sub
    End Class
End Namespace